<script  setup >
import { ref, onBeforeMount, nextTick } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus';
import { Plus, Edit, Delete } from '@element-plus/icons-vue'

import MenuDialog from './MenuDialog.vue'
import { getMenuList, menuTreeDel } from '@/api/menu/index'
import { split } from 'postcss/lib/list';

let dialogVisible = ref(false)
const loading = ref(false)
const menuDialog = ref(null)
let tableData = ref([])

let getData = async () => {
  loading.value = true
  let data = await getMenuList();
  loading.value = false
  tableData.value = data.data.list
  console.log('tableData', tableData)
}

const handleEdit = (row) => {
  dialogVisible.value = true
  if (!row.pid) {
    row.pid = ''
  }
  row.pid = row.pid + ''
  nextTick(() => {
    let pathArray = []
    if (typeof row.path === 'string') {
      row.path = row.path.split('/')
      row.path.forEach(item => {
        if (item) {
          pathArray.push(item)
        }
      });
      pathArray[0] = '/' + pathArray[0]
      row.path = pathArray
      console.log(pathArray)
    }

    menuDialog.value.form = Object.assign(menuDialog.value.form, row)

  })
}

const handleDel = (row) => {
  ElMessageBox.confirm('确认要删除 ? 一旦删除无法恢复', '提示', { type: 'warning' }).then(async () => {
    let res = await menuTreeDel({ id: row.id })
    if (res) {
      ElMessage({ message: '删除成功', type: 'success' })
      getData();
    }
  }).catch(() => {

  })

}


onBeforeMount(() => {
  getData()
})
</script>
<template>
    <el-button @click="handleEdit" plain type="primary" :icon="Plus">新增</el-button>
    <el-table v-loading="loading" :data="tableData" style="width: 100%; margin-top: 20px" row-key="id" border
        default-expand-all>
        <el-table-column prop="name" label="名称" />
        <el-table-column prop="type" label="类型">
            <template #default="scope">
                {{ scope.row.type == 1 ? '按钮' : '菜单' }}
            </template>
        </el-table-column>
        <el-table-column lable="操作">
            <template #default="scope">
                <el-button link @click="handleEdit(scope.row)" :icon="Edit" type="primary">编辑</el-button>
                <el-button link @click="handleDel(scope.row)" :icon="Delete" type="primary">删除</el-button>
            </template>
        </el-table-column>
    </el-table>
    <MenuDialog ref="menuDialog" @saveSuccess="getData" :dialog-visible="dialogVisible"
        @closeDialog="dialogVisible = false" />
</template>

